<template>
  <div :class="extendClass" class="upload_box upload_btn click_to_green">
      <x-img 
          :src="img"
          :default-src="defaultImg"
        />
    <input
      ref="uploadFile"
      @change="onChange"
      type="file"
      accept="image/*"
      class="upload_file_input"
    >
  </div>
</template>

<script>
import baseService from "../shared/service/baseService";
import { fileUtil } from '../assets/js/fileUtil';
import * as qiniu from "qiniu-js";
import { XImg } from "vux";


export default {
  components: {
    XImg,
  },
  name: "imgUpload",
  props: ["imgSrc", "width", "height",'defaultSrc','extClass'], /* uploadOkEvent 文件上传完成事件 */
  data() {
    var img="";
    if (this.src) {
      img = this.src;
    }
    var defaultImg = img;
    if(this.defaultSrc){
        defaultImg = this.defaultSrc;
    }
    var extendClass = "";
    if(this.extClass){
        extendClass = this.extClass;
    }
    return {
      img:img,
      defaultImg:defaultImg,
      extendClass:extendClass,
      domain: "",
      token: "",
      w: this.width || "5rem",
      h: this.height || "5rem",
      config: {
        useCdnDomain: true,
        disableStatisticsReport: false,
        retryCount: 6,
        region: qiniu.region.z0
      },
      putExtra: {
        fname: "",
        params: {},
        mimeType: null
      }
    };
  },
  created() {
    this.getDomain();
    this.getToken();
  },
  methods: {
    getDomain() {
      baseService.qiniuDomain().then(res => {
        this.domain = res.data;
      });
    },
    getToken() {
      baseService.qiniuToken().then(res => {
        this.token = res.data;
      });
    },
    setImgSrc(src){
      this.img=src;
    },
    upload(file) {
      let observable;
      if (file) {
        const key = file.name;
        this.putExtra.params["x:name"] = key.split(".")[0];

        //文件上传事件
        const error = () => {
            this.$vux.loading.hide();
          this.$vux.alert.show({
            title: "提示",
            content: "上传出错，请重试！"
          });
        };
        //文件上传事件
        const complete = res => {
          this.$vux.loading.hide();
          if (res.key && res.key.match(/\.(jpg|jpeg|png|gif)$/)) {
            var src =  this.domain + res.key;
            this.$emit('uploadOkEvent',src);
          }
        };

        const subObject = {
          // next: next,
          error: error,
          complete: complete
        };
        // 调用sdk上传接口获得相应的observable，控制上传和暂停
        observable = qiniu.upload(file,key,this.token,this.putExtra, this.config);
        // 上传
        this.$vux.loading.show({ text: "Loading" });
        observable.subscribe(subObject);
      }
    },
    onChange() {
      const file = event.target.files[0];
      this.upload(file);
      //大于1025kb 的文件压缩一下
   //   fileUtil.getCompress(file,{size:1025},this.upload);
    }
  }
};
</script>

<style scoped>
</style>